package com.logicalthinking.socialmall.biz;

import com.github.chenlijia1111.commonModule.biz.CouponBiz;
import com.github.chenlijia1111.commonModule.biz.ProductBiz;
import com.github.chenlijia1111.commonModule.common.requestVo.coupon.AddExpressCouponParams;
import com.github.chenlijia1111.commonModule.common.requestVo.product.GoodAddParams;
import com.github.chenlijia1111.commonModule.common.responseVo.product.AdminProductVo;
import com.github.chenlijia1111.commonModule.entity.Product;
import com.github.chenlijia1111.commonModule.service.IdGeneratorServiceI;
import com.github.chenlijia1111.commonModule.service.ProductServiceI;
import com.github.chenlijia1111.utils.common.Result;
import com.github.chenlijia1111.utils.common.constant.BooleanConstant;
import com.github.chenlijia1111.utils.database.mybatis.pojo.PageInfo;
import com.github.chenlijia1111.utils.list.Lists;
import com.logicalthinking.socialmall.common.vo.requestVo.product.*;
import com.logicalthinking.socialmall.common.vo.responseVo.product.AdminProductListVo;
import com.logicalthinking.socialmall.common.vo.responseVo.product.AppProductListVo;
import com.logicalthinking.socialmall.common.vo.responseVo.product.SocialAdminProductVo;
import com.logicalthinking.socialmall.common.vo.responseVo.product.SocialAppProductVo;
import com.logicalthinking.socialmall.entity.ClientUser;
import com.logicalthinking.socialmall.entity.ProductAppend;
import com.logicalthinking.socialmall.service.ClientUserServiceI;
import com.logicalthinking.socialmall.service.ProductAppendServiceI;
import com.logicalthinking.socialmall.service.SocialProductServiceI;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 产品
 *
 * @author Chen LiJia
 * @since 2020/2/18
 */
@Service
public class MallProductBiz {

    @Autowired
    private ProductBiz productBiz;//产品
    @Autowired
    private CouponBiz couponBiz;//券
    @Autowired
    private ProductAppendServiceI productAppendService;//产品补充参数
    @Autowired
    private ProductServiceI productService;//产品
    @Autowired
    private SocialProductServiceI socialProductService;//产品
    @Autowired
    private ClientUserServiceI clientUserService;//用户

    @Autowired
    @Qualifier("productIdGeneratorService")
    private IdGeneratorServiceI productIdGeneratorService;

    /**
     * 添加产品
     *
     * @param params
     * @return
     */
    @Transactional
    public Result add(MallProductAddParams params) {

        //当前用户
        Optional<ClientUser> optional = clientUserService.currentUser();
        if (!optional.isPresent()) {
            return Result.notLogin();
        }

        ClientUser clientUser = optional.get();
        if (Objects.equals(1, clientUser.getUserType())) {
            return Result.failure("用户未认证");
        }

        Result result = productBiz.add(params, productIdGeneratorService);
        //买完之后在添加一些额外的补充参数
        if (result.getSuccess() && Objects.nonNull(result.getData())) {
            String productId = (String) result.getData();

            ProductAppend productAppend = new ProductAppend();
            BeanUtils.copyProperties(params, productAppend);
            productAppend.setProductId(productId);

            Double minPrice = Double.MAX_VALUE;
            Double maxPrice = Double.MIN_VALUE;
            //获取最小价格 //获取最大价格
            List<GoodAddParams> goodList = params.getGoodList();
            for (GoodAddParams goodAddParams : goodList) {
                Double price = goodAddParams.getPrice();
                minPrice = Math.min(price, minPrice);
                maxPrice = Math.max(price, maxPrice);
            }
            productAppend.setMinPrice(minPrice);
            productAppend.setMaxPrice(maxPrice);
            //初始化销量
            productAppend.setSalesCount(0);
            //如果设置了运费,添加运费的优惠券,用于订单价格计算
            if (Objects.nonNull(params.getFreight())) {
                //设置运费
                productAppend.setFreight(params.getFreight());
                //添加运费券
                AddExpressCouponParams couponParams = new AddExpressCouponParams();
                couponParams.setCouponName("物流券");
                couponParams.setCouponTotalCount(Integer.MAX_VALUE);
                couponParams.setCreateUserType(3);
                couponParams.setCreateUserId(String.valueOf(clientUser.getId()));
                couponParams.setExpressMoney(params.getFreight());
                couponParams.setConditionMoney(9999999.00);
                couponParams.setConditionCount(99999999);
                Result couponResult = couponBiz.addExpressCoupon(couponParams);
                if(couponResult.getSuccess()){
                    String couponJson = (String) couponResult.getData();
                    //关联运费券
                    productAppend.setFreightCoupon(couponJson);
                }
            }
            productAppendService.add(productAppend);


        }
        return result;
    }


    /**
     * 编辑产品
     *
     * @param params
     * @return
     */
    public Result update(MallProductUpdateParams params) {

        //当前用户
        Optional<ClientUser> optional = clientUserService.currentUser();
        if (!optional.isPresent()) {
            return Result.notLogin();
        }

        ClientUser clientUser = optional.get();
        if (Objects.equals(1, clientUser.getUserType())) {
            return Result.failure("用户未认证");
        }

        Result result = productBiz.update(params);
        //买完之后在添加一些额外的补充参数
        if (result.getSuccess()) {
            String productId = params.getId();

            ProductAppend productAppend = new ProductAppend();
            BeanUtils.copyProperties(params, productAppend);
            productAppend.setProductId(productId);

            Double minPrice = Double.MAX_VALUE;
            Double maxPrice = Double.MIN_VALUE;
            //获取最小价格 //获取最大价格
            List<GoodAddParams> goodList = params.getGoodList();
            for (GoodAddParams goodAddParams : goodList) {
                Double price = goodAddParams.getPrice();
                minPrice = Math.min(price, minPrice);
                maxPrice = Math.max(price, maxPrice);
            }
            productAppend.setMinPrice(minPrice);
            productAppend.setMaxPrice(maxPrice);
            //如果设置了运费,添加运费的优惠券,用于订单价格计算
            if (Objects.nonNull(params.getFreight())) {
                //设置运费
                productAppend.setFreight(params.getFreight());
                //添加运费券
                AddExpressCouponParams couponParams = new AddExpressCouponParams();
                couponParams.setCouponName("物流券");
                couponParams.setCouponTotalCount(Integer.MAX_VALUE);
                couponParams.setCreateUserType(3);
                couponParams.setCreateUserId(String.valueOf(clientUser.getId()));
                couponParams.setExpressMoney(params.getFreight());
                couponParams.setConditionMoney(Double.MAX_VALUE);
                couponParams.setConditionCount(Integer.MAX_VALUE);
                Result couponResult = couponBiz.addExpressCoupon(couponParams);
                if(couponResult.getSuccess()){
                    String couponJson = (String) couponResult.getData();
                    //关联运费券
                    productAppend.setFreightCoupon(couponJson);
                }
            }
            productAppendService.update(productAppend);
        }
        return result;
    }

    /**
     * 上架
     *
     * @param productId
     * @return
     */
    public Result shelfUp(String productId) {
        //查询判断产品是否存在
        Product product = productService.findByProductId(productId);
        if (Objects.isNull(product) || Objects.equals(product.getDeleteStatus(), BooleanConstant.YES_INTEGER)) {
            return Result.failure("数据不存在");
        }

        product.setShelfStatus(BooleanConstant.YES_INTEGER);
        return productService.update(product);
    }

    /**
     * 批量上架
     *
     * @param productIdList
     * @return
     */
    @Transactional
    public Result batchShelfUp(List<String> productIdList) {
        if (Lists.isEmpty(productIdList)) {
            return Result.failure("未选中数据");
        }

        for (String productId : productIdList) {
            Result result = shelfUp(productId);
            if (!result.getSuccess()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return Result.success("操作成功");
    }

    /**
     * 下架
     *
     * @param productId
     * @return
     */
    public Result shelfDown(String productId) {
        //查询判断产品是否存在
        Product product = productService.findByProductId(productId);
        if (Objects.isNull(product) || Objects.equals(product.getDeleteStatus(), BooleanConstant.YES_INTEGER)) {
            return Result.failure("数据不存在");
        }

        product.setShelfStatus(BooleanConstant.NO_INTEGER);
        return productService.update(product);
    }

    /**
     * 批量下架
     *
     * @param productIdList
     * @return
     */
    @Transactional
    public Result batchShelfDown(List<String> productIdList) {
        if (Lists.isEmpty(productIdList)) {
            return Result.failure("未选中数据");
        }

        for (String productId : productIdList) {
            Result result = shelfDown(productId);
            if (!result.getSuccess()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return Result.success("操作成功");
    }


    /**
     * 删除商品
     *
     * @param productId
     * @return
     */
    public Result delete(String productId) {
        //查询判断产品是否存在
        Product product = productService.findByProductId(productId);
        if (Objects.isNull(product) || Objects.equals(product.getDeleteStatus(), BooleanConstant.YES_INTEGER)) {
            return Result.failure("数据不存在");
        }

        product.setDeleteStatus(BooleanConstant.YES_INTEGER);
        return productService.update(product);
    }

    /**
     * 批量删除
     *
     * @param productIdList
     * @return
     */
    @Transactional
    public Result batchDelete(List<String> productIdList) {
        if (Lists.isEmpty(productIdList)) {
            return Result.failure("未选中数据");
        }

        for (String productId : productIdList) {
            Result result = delete(productId);
            if (!result.getSuccess()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return Result.success("操作成功");
    }

    /**
     * 后台查询商品列表
     *
     * @return
     */
    public Result adminListPage(AdminProductQueryParams params) {
        List<AdminProductListVo> list = socialProductService.adminListPage(params);
        PageInfo<AdminProductListVo> pageInfo = new PageInfo<>(list);
        return Result.success("查询成功", pageInfo);
    }

    /**
     * 查询商品详情
     *
     * @param productId
     * @return
     */
    public Result adminFindInfoById(String productId) {
        AdminProductVo adminProductVo = productService.findAdminProductVoByProductId(productId);
        if (Objects.isNull(adminProductVo)) {
            return Result.failure("数据不存在");
        }

        //进行转化
        SocialAdminProductVo vo = new SocialAdminProductVo();
        BeanUtils.copyProperties(adminProductVo, vo);
        //添加附加数据
        ProductAppend productAppend = productAppendService.findByProductId(productId);
        if (Objects.nonNull(productAppend)) {
            vo.setTransactionTypeSupportOnline(productAppend.getTransactionTypeSupportOnline());
            vo.setTransactionTypeSupportInperson(productAppend.getTransactionTypeSupportInperson());
            //生成交易类型
            vo.createTransactionTypeName();
            //发布地址
            vo.setReleaseAddress(productAppend.getReleaseAddress());
            //运费
            vo.setFreight(productAppend.getFreight());
        }

        return Result.success("查询成功", vo);
    }


    /**
     * 客户端查询商品列表
     *
     * @param params
     * @return
     */
    public Result appListPage(AppProductQueryParams params) {

        List<AppProductListVo> list = socialProductService.appListPage(params);
        PageInfo<AppProductListVo> pageInfo = new PageInfo<>(list);
        return Result.success("查询成功", pageInfo);
    }

    /**
     * 客户端查询商品详情
     *
     * @param params
     * @return
     */
    public Result appFindById(AppFindProductInfoParams params) {
        //判断是否存在
        AdminProductVo adminProductVo = productService.findAdminProductVoByProductId(params.getProductId());
        if (Objects.isNull(adminProductVo)) {
            return Result.failure("数据不存在");
        }

        SocialAppProductVo vo = new SocialAppProductVo();
        BeanUtils.copyProperties(adminProductVo, vo);

        //获取其他数据信息
        ProductAppend productAppend = productAppendService.findByProductId(params.getProductId());
        if (Objects.nonNull(productAppend)) {
            vo.setTransactionTypeSupportOnline(productAppend.getTransactionTypeSupportOnline());
            vo.setTransactionTypeSupportInperson(productAppend.getTransactionTypeSupportInperson());
            //生成交易类型
            vo.createTransactionTypeName();
            //发布地址
            vo.setReleaseAddressLongitude(productAppend.getReleaseAddressLongitude());
            vo.setReleaseAddressLatitude(productAppend.getReleaseAddressLatitude());
            vo.setReleaseAddress(productAppend.getReleaseAddress());
            //价格范围
            if (Objects.equals(productAppend.getMinPrice(), productAppend.getMaxPrice())) {
                vo.setPriceRange(String.valueOf(productAppend.getMinPrice()));
            } else {
                StringBuilder sb = new StringBuilder();
                sb.append(productAppend.getMinPrice());
                sb.append("-");
                sb.append(productAppend.getMaxPrice());
                vo.setPriceRange(sb.toString());
            }
            //销量
            vo.setSalesCount(productAppend.getSalesCount());
            //经纬度
            vo.setReleaseAddressLongitude(productAppend.getReleaseAddressLongitude());
            vo.setReleaseAddressLatitude(productAppend.getReleaseAddressLatitude());
            //计算距离
            vo.calculateDistance(params.getUserLongitude(), params.getUserLatitude());
            //运费
            vo.setFreight(productAppend.getFreight());
        }

        return Result.success("查询成功", vo);
    }


}
